$(function() {
	$(".link-success").click(function() {
		location.href = "paySuccess.html";
	})
})

import {
	checkLogin,
} from './auth.js'
new Vue({
	el: '#app',
	data: {
		IS_LOGIN: null,
		searchKey: '', // 搜索的关键词
		// 查询参数,字符串形式
		param: '',
		// 查询参数列表,数组形式
		queryParamList: [],
		cartList: [],
		totalPrice: 0,
		totalNum: 0,
		addressList: [],
		checkedAddress: null
	},
	async created() {
		this.IS_LOGIN = await checkLogin()
		if (this.IS_LOGIN == null) {
			location.href = '/'
		}
		this.getPathParam()
		this.getCartList()
		this.getAddressList()
	},

	methods: {
		// 跳转支付页面
		goToPay() {
			this.saveOrder()
			// location.href = `payment.html?param=${this.param},${this.checkedAddress}`
		},
		// 保存订单
		async saveOrder() {
			const res = await request.post('/order/saveOrder', {
				cids: this.queryParamList,
				aid: this.checkedAddress
			})
			const orderId = res.data
			location.href = `payment.html?param=${orderId}`
		},
		// 获取地址列表
		async getAddressList() {
			const res = await request.get('/address/getAddressList')
			this.addressList = res.data
			for (let i = 0 ;i < this.addressList.length ; i ++ ) {
				if (this.addressList[i].isDefault == 1) {
					this.checkedAddress = this.addressList[i].aid
					break;
				}
			}
		},
		// 获取购物车列表
		async getCartList() {
			const res = await request.get('/cart/getOrderListByIds',{
				params: {
					ids: this.param
				}
			})
			this.cartList = res.data
			this.totalNum = 0
			this.totalPrice = 0
			for (let i = 0; i < this.cartList.length; i++) {
				const element = this.cartList[i]
				this.totalPrice += element.price * element.num
				this.totalNum += element.num
			}
		},
		// 获取路径参数
		getPathParam() {
			const pathParam = location.search.substring(location.search.lastIndexOf('=') + 1)
			this.param = pathParam
			this.queryParamList = pathParam.split(',')
			console.log(this.param, this.queryParamList)
		},
		// 查找商品
		searchProduct() {
			console.log('查找商品:')
			location.href = `../web/search.html?searchKey=${this.searchKey}`
		},
		// 退出登录
		logout() {
			localStorage.removeItem('token')
			location.href = '/'
		},
	}
})